package giit.computerbase.server;

import giit.computerbase.dao.SQL;
import giit.computerbase.dao.SQLFactory;
import giit.computerbase.util.Application;
import giit.computerbase.util.Hash;

import java.util.*;

/**
 * User: tum0r
 * Package Name: giit.computerbase.server
 * Time: 2018/11/12 Monday 19:05:39
 */
public class LoginServer {
    private Hash hash;
    private SQL sql;

    public LoginServer() {
        try {
            sql = SQLFactory.getSQL();
            sql.open((String) Application.getConfig().databaseConfig.get("address"),
                    (int) Application.getConfig().databaseConfig.get("port"),
                    Application.DATABASE_NAME,
                    (String) Application.getConfig().databaseConfig.get("encode"),
                    (String) Application.getConfig().databaseConfig.get("user"),
                    (String) Application.getConfig().databaseConfig.get("password"));
            hash = new Hash();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Object[] checkUser(String username, String password, String typeName) {
        Object[] result = new Object[2];
        result[0] = false;
        password = hash.encryption(hash.encryption(password, Hash.SHA256), Hash.MD5);
        ArrayList<HashMap<String, Object>> temp = sql.query("select id from user_type where name=?", new Object[]{typeName});
        Iterator<HashMap<String, Object>> iterator = temp.iterator();
        if (iterator.hasNext()) {
            HashMap<String, Object> information = iterator.next();
            String typeID = (String) information.get("id");
            temp = sql.query("select organization_id,name from user where name=? and password=? and user_type_id=?", new Object[]{username, password, typeID});
            if (temp.size() == 1) {
                iterator = temp.iterator();
                information = iterator.next();
                String id = (String) information.get("organization_id");
                temp = sql.query("select name from organization where id=?", new Object[]{id});
                iterator = temp.iterator();
                information = iterator.next();
                result[0] = true;
                result[1] = addLogin((String) information.get("name"), typeName, username);
            }
        }
        return result;
    }

    private String addLogin(String organization, String usertype, String user) {
        String cookies = getCookies();
        while (isLogin(cookies)) {
            cookies = getCookies();
        }
        sql.add("insert into login values(?,?,?,?,?)", new Object[]{organization, usertype, user, cookies, new Date().getTime()});
        return cookies;
    }

    private String getCookies() {
        StringBuffer result = new StringBuffer();
        Random random = new Random();
        int n;
        char temp = '0';
        for (int i = 0; i < (int) Application.getConfig().databaseConfig.get("cookie-length"); i++) {
            n = random.nextInt(3);
            switch (n) {
                case 0:
                    temp = (char) ('0' + random.nextInt(10));
                    break;
                case 1:
                    temp = (char) ('a' + random.nextInt(26));
                    break;
                case 2:
                    temp = (char) ('A' + random.nextInt(26));
                    break;
            }
            result.append(temp);
        }
        return result.toString();
    }

    public boolean deleteLogin(String cookies) {
        return sql.delete("delete from login where cookies=?", new Object[]{cookies});
    }

    public void clearTimeOut(long time) {
        long now = new Date().getTime();
        ArrayList<HashMap<String, Object>> logins = getLogin();
        ArrayList<String> willDelete = new ArrayList<>();
        Iterator<HashMap<String, Object>> loginIterator = logins.iterator();
        while (loginIterator.hasNext()) {
            HashMap<String, Object> temp = loginIterator.next();
            if (now - (long) temp.get("time") >= time) {
                willDelete.add((String) temp.get("cookies"));
            }
        }
        Iterator<String> deleteIterator = willDelete.iterator();
        while (deleteIterator.hasNext()) {
            deleteLogin(deleteIterator.next());
        }
    }

    public boolean isLogin(String cookies) {
        boolean flag = sql.query("select * from login where cookies=?", new Object[]{cookies}).size() == 1;
        if (flag) {
            sql.alter("update login set time=? where cookies=?", new Object[]{new Date().getTime(), cookies});
        }
        return flag;
    }

    public ArrayList<HashMap<String, Object>> getUserInformation(String cookies) {
        return sql.query("select organization,user_type,user from login where cookies=?", new Object[]{cookies});
    }

    public int logigNumber() {
        return getLogin().size();
    }

    private ArrayList<HashMap<String, Object>> getLogin() {
        return sql.query("select * from login", null);
    }
}
